package com.example.blogapi.service;

import com.example.blogapi.dao.CategoryDao;
import com.example.blogapi.model.Category;

import java.sql.SQLException;
import java.util.List;

public class CategoryService {
    private final CategoryDao categoryDao;

    public CategoryService() {
        this.categoryDao = new CategoryDao();
    }

    public List<Category> getAllCategories() throws SQLException {
        return categoryDao.findAll();
    }

    public Category getCategoryById(Long id) throws SQLException {
        return categoryDao.findById(id);
    }

    public Category createCategory(Category category) throws SQLException {
        // 检查分类名是否已存在
        Category existingCategory = categoryDao.findByName(category.getName());
        if (existingCategory != null) {
            throw new IllegalArgumentException("Category name already exists");
        }
        
        return categoryDao.create(category);
    }

    public Category updateCategory(Long id, Category category) throws SQLException {
        Category existingCategory = categoryDao.findById(id);
        if (existingCategory == null) {
            throw new IllegalArgumentException("Category not found");
        }

        // 如果分类名已更改，检查新分类名是否已存在
        if (!existingCategory.getName().equals(category.getName())) {
            Category categoryWithSameName = categoryDao.findByName(category.getName());
            if (categoryWithSameName != null) {
                throw new IllegalArgumentException("Category name already exists");
            }
        }

        category.setId(id);
        category.setCreatedAt(existingCategory.getCreatedAt());
        return categoryDao.update(category);
    }

    public boolean deleteCategory(Long id) throws SQLException {
        Category existingCategory = categoryDao.findById(id);
        if (existingCategory == null) {
            throw new IllegalArgumentException("Category not found");
        }
        
        return categoryDao.delete(id);
    }
}